/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ChatNI;

import common.Message;
import MVC.*;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.LinkedList;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * ListenUDP
 * Class in charge of listening to the chosen UDP port
 * This class inherits a thread
 * @author Duy Duc ,Metangmo
 */

public class ListenUDP extends Thread{

    private java.net.DatagramSocket ds;
    private final static int size = 1000;
    private Message message;
    private ChatController controller;
    
    /**
     * Constructor
     * @param ds
     *        DatagramSocket used for the recipient of a message
     * @param controller
     *        Instance of the ChatController
     * @param fileMessage
     *        Queue storing the received message waiting for being treated
     * @throws SocketException 
     */
    public ListenUDP(DatagramSocket ds, ChatController controller , LinkedList<Message> fileMessage )throws SocketException  {
        super();
        this.ds = ds;
        this.controller = controller;
        
    }
    
    /**
     * run:
     * thread collects the content of the received message on the listened port
     * and transmits this message to the controller for the treatment
     */
    public void run() {
        byte[] buffer = new byte[size];
        
        while (true) {
            try {
                
                DatagramPacket dp = new DatagramPacket(buffer, size);
                ds.receive(dp);
                
                ByteArrayInputStream baos = new ByteArrayInputStream(buffer); 
                ObjectInputStream ois = new ObjectInputStream(baos);
                try {
                    
                    //Message is received
                    Object mess  = ois.readObject();
                    message = (Message) mess;
                    
                    //The ChatController performs  the action of treating the received message
                    controller.performReceiveMessage(message);
                    
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(ListenUDP.class.getName()).log(Level.SEVERE, null, ex);
                    System.out.println("Error reception!!!");
                }

            } catch (IOException ex) {
                //System.out.println("Erreur lecture!!! ");
            }

        }
    }

    /**
     * getMessage:
     * function collects the received message
     * @return
     *        Received message
     */
    public Message getMessage() {
        return message;
    }
}
